package com.xsl.lession02.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.xsl.lession02.pojo.ElectronicFence;
import com.xsl.lession02.pojo.FenceLocationPoint;
import com.xsl.lession02.pojo.MonitoredPerson;
import com.xsl.lession02.vo.ErrorResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
public class ElectronicFenceService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private BaiduService baiduService;

    /**
     * 新增电子围栏
     *
     * @param electronicFence
     * @return
     */
    public Object createElectronicFence(ElectronicFence electronicFence) {
        //对数据做校验
        if (StrUtil.isEmpty(electronicFence.getName()) || CollUtil.isEmpty(electronicFence.getMutiPoints())) {
            return ErrorResult.builder()
                    .errCode("500")
                    .errMessage("电子围栏的名称或多边形的坐标为空！").build();
        }

        //调用百度地图的api创建电子围栏
        Long fenceId = this.baiduService.createElectronicFence(electronicFence);
        if (null == fenceId) {
            return ErrorResult.builder()
                    .errCode("501")
                    .errMessage("创建电子围栏失败！").build();
        }

        electronicFence.setFenceId(fenceId);
        electronicFence.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(electronicFence);

        return null;
    }

    /**
     * 创建监控对象
     *
     * @param monitoredPerson
     * @return
     */
    public Object addMonitoredPerson(MonitoredPerson monitoredPerson) {

        this.baiduService.addMonitoredPerson(monitoredPerson);

        return null;
    }


    /**
     *  判断电子围栏
     *
     * @param
     * @return
     */
    public Object querystatusbylocation(FenceLocationPoint fenceLocationPoint) {

        //调用百度地图的api创建电子围栏
        Long fenceId = this.baiduService.querystatusbylocation(fenceLocationPoint);
        if (null == fenceId) {
            return ErrorResult.builder()
                    .errCode("501")
                    .errMessage("创建电子围栏失败！").build();
        }
        return null;
    }

    /**
     * 根据id查询电子围栏数据
     *
     * @param id
     * @return
     */
    public Object queryElectronicFenceById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), ElectronicFence.class);
    }

}
